package com.chengliang.zuoye.bean;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import tk.mybatis.mapper.annotation.KeySql;

import javax.persistence.Id;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author jerry
 */
@Data
public class User implements Serializable,UserDetails {

    @Id
    @KeySql(useGeneratedKeys = true)
    private Integer id;
    /**
     * 姓名
     */
    private String name;

    /**
     * 登陆邮箱
     */
    private String email;
    /**
     * 密码
     */
    @JsonIgnore
    private String password;
    /**
     * 性别
     * 0未知
     * 1男
     * 2女
     */
    private Integer sex;

    /**
     * 头像
     */
    private String  headImg;
    /**
     * 注册时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime regTime;
    /**
     * 班级ID
     */
    private Integer classId;
    /**
     * 班级对象信息
     */
    private Classes classes;
    /**
     * 是否启用
     * 0启用
     * 1禁用
     */
    private Integer status;
    /**
     * 角色信息
     */
    private Role role;
    private Integer roleId;

    /**
     * 该用户的角色 拥有的菜单项
     */
    private List<Integer> menuIds;

    /**
     * @return
     * 系统单角色模式 即一个用户只有一个角色
     */
    @JsonIgnore
    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        if(role!=null){
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
        }
        return authorities;
    }

    @Override
    public String getUsername() {
        return email;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        if(status==null){
            return false;
        }
        return status == 0;
    }
}
